<%@ page language="java" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>

//应用上下文:document
//var _documentContext = "<%=request.getContextPath() %>";

//各业务模块，必须定义的变量（框架issue.js文件中需用到，不要修改变量名）
var _title;	//业务标题
var _issueId; //业务主键
//var _issueType="todo";

var _doSurplusWork = _documentContext + "/docDispatch/doSurplusWork";//（流程启动成功后业务数据的相关操作）业务模块自己定义的业务处理方法，以供框架在提交完成后，进行触发

var officeData=new Array();//正文数据

var olddisplayNumberReceive = "<c:out value='${docIssue.displayNumberReceive}'/>";

var signDate = "<c:out value='${signDate}'/>";//会签完成时限

/**
 * 业务数据初始化
 */
$(function(){
	
	$("#hide_").hide();
	$("#hide_expeireTime").hide();
	
	//禁止后退键 作用于Firefox、Opera
	 document.onkeypress=banBackSpace;
	 //禁止后退键 作用于IE、Chrome
	 document.onkeydown=banBackSpace;
	
	contentControlId="docReceiveTable";//正文部分容器id,用于浮动菜单显示隐藏正文要素
	_issueId=$("#docId").val();//流程id,查询已有附件条件
	
	if($.type(inintCorrelationIssuePage) == "function"){
		inintCorrelationIssuePage();
		
	}
	addValid();
	
	if($("#displayNumberReceive").val()==null||$("#displayNumberReceive").val()==''){
		if($("#isStart").val()=="0"&&_issueType=="done"){
			
		}else{
			buildDisplayNumberDiv($("#formType").val());
		}
	}
	
	_printFormUrl = _documentContext+"/docReceive/showForm/"+_issueId;//浮动菜单，打印处理单
	
	if(_workEffortId=="isNew"&&$("#docReceiveType").val()=='ER'){
		$("#receiveMain").show();
		getReceiveAdviceByIndex(-2);
	}else{
		$("#receiveMain").hide();
	}
	if(actionPermissionJson.ApprovalKey=="true"){
		$("#keyword").val("1");
	}
	
	
	if(null!=signDate && ''!=signDate){
		$("#signDateShow").show();
	}else{
		$("#signDateShow").hide();
	}
	
	//用于清除未启动的时候通过done进入查看的时候登记人和编号
	if($("#isStart").val()=="0"&&_issueType=="done"){
		$("#drafter").val("");
	}
});

/**
 * 框架页面调用的保存方法
 */
function _saveOAdata(){
	if(!checkPageItems()){//页面验证不通过
		return 1;
	}
	var status = submitOAdata();
	if(status != 100)
	{
		return 2;
	}
	return 0;//0:保存成功，1：验证未通过，2：数据保存错误
}

/**
 * 验证
 */
function checkPageItems(){
	return $("#docIssueForm").form('validate');
}

/**
 * 保存业务数据
 * 返回值100:正常、200:数据保存失败、300:正文及附件保存失败、400:附件上传失败
*/
function submitOAdata(){
	if($("#displayNumberReceive").val()==null||$("#displayNumberReceive").val()==''){
		var type = $("#formType").val();
		if(type=="1"){
			$("#displayNumberReceive").val($("#numYear").val()+"-"+$("#num").val());
		}else if(type=="2"){
			$("#displayNumberReceive").val($("#numOrg").val()+"-"+$("#numYear").val()+"-"+$("#numMonth").val()+"-"+$("#num").val());
		}else if(type=="3"){
			$("#displayNumberReceive").val($('#numLine').combobox('getValue')+"-"+$('#numLineName').combobox('getValue')+"-"+$("#numYear").val()+"-"+$("#num").val());
		}else{
			alert("参数错误");
			return;
		}
	}
	if(olddisplayNumberReceive!=""&&olddisplayNumberReceive!=$("#displayNumberReceive").val()){
		$("#saveFlag").val("2");
	}
	var submitState=0;
	$.ajax({//ajax保存表单基本信息
		   type: "POST",
		   url: "<c:url value='/receive/savePaperIssue' />",
		   data: $('#docIssueForm').serialize(),
		   dataType: "json",
		   async:false,
		   success: function(msg){
		     if(msg.state=="200"){
		    	 $("#docId").val(msg.docIssue.docId);
		    	 _title=$("#docName").val();
		    	 _issueId=msg.docIssue.docId;
		    	 olddisplayNumberReceive = $("#displayNumberReceive").val();
		    	 $("#saveFlag").val("");
		    	 submitState=fileUploadSaveFileFt(_issueId,"0","0","AS","")?100:500;//保存附件
		     }else{
		    	 //$.messager.alert("提示","保存数据失败");
		    	 submitState=500;
		     }
		   }
		});
	return submitState;
}


//绑定验证
function addValid(){
	var todoFlag=_issueType=="todo"&&actionPermissionJson.EditForm=="true";
	var isNewFlag=_workEffortId=="isNew";
	var editFlag = isNewFlag || todoFlag;
	//纸质可编辑部分
	var prEditFlag=(isNewFlag || todoFlag)&&$("#docReceiveType").val()=="PR";
	//如果是待办则显示编辑正文那一列 已办则没有
	if(!todoFlag){
//		$("#showDocTr").hide();
		$("#displayNumberImg").hide();
		$("#displayNumberB").attr("disabled","disabled");
	}
	
	$.ajax({
		   type: "POST",
		   url: "<c:url value='/receive/querySynOfficial' />",
		   data:"docId="+_issueId,
		   dataType: "json",
		   async:false,
		   success: function(msg){
		     if(msg.state=="200"){
		    	 if(prEditFlag){
		    		 $("#editReceiveWordDiv").show();
		    			$("#viewReceiveWordDiv").hide();
		    	 }else{
				 		$("#editReceiveWordDiv").hide();
						$("#viewReceiveWordDiv").show();
		    	 }
		     }else{
		    	 if(prEditFlag){
		    			$("#editReceiveWordDiv").show();
		    			$("#viewReceiveWordDiv,#printWord,#downloadWord").hide();
		    		}else{
		    			$("#showDocTr").hide();
				 		$("#editReceiveWordDiv").hide();
						$("#viewReceiveWordDiv").hide();
		    		}
		    	 
		     }
		     $("#editManuscriptWordDiv,#editWordDiv,#viewManuscriptWordDiv,#viewWordDiv").remove();
		   }
		});
	var controlId="fileUpload";//自定义控件名前缀
	var delFlag=prEditFlag&&(actionPermissionJson.ModifyAttach=="true"||isNewFlag)?"1":"0";//显示删除按钮：0，不显示；1，显示
	var addFlag=prEditFlag&&(actionPermissionJson.ModifyAttach=="true"||isNewFlag)?"1":"0";//添加按钮可用：0，不可用；1，可用
	var showControlFlag=prEditFlag&&(actionPermissionJson.ModifyAttach=="true"||isNewFlag)?"1":"0";//显示file控件和上传按钮：0，不显示；1，显示
	//var docType="";//流程状态：为done时候控制file控件和上传按钮不显示----issue.js已有	
	var attachNo="0";//查询已有附件条件
	var attachVersion="0";//查询已有附件条件
	var attachType="AS";//查询已有附件条件
	
	$("#fileDiv").panel({
	    href:_synergyContext+'/basic/synAttach/gotoSynAttachPage?docId='
	    	+_issueId+'&controlId='+controlId+'&delFlag='+delFlag+'&addFlag='+addFlag
	    	+'&showControlFlag='+showControlFlag+'&docType='+_issueType
	    	+"&attachNo="+attachNo+"&attachVersion="+attachVersion
			   +"&attachType="+attachType,
	    border:false,//不显示边框
	    cache:false//不从缓存加载面板
	});
	
	
	if($("select[id='docReceiveCode']").size()==1){
		$("#docReceiveCode").combobox({
			editable:false,
			disabled:!editFlag
		});
	}
	
	$("#displayNumber").textbox({
		editable:prEditFlag
	});
	
	//份数
	$("#printNum").numberbox({
//		required: true,
	    min:1,
	    precision:0,
	    editable:editFlag
	});
	
	//收文转发文
	var _fromSjFlag = "<c:out value='${fromSjFlag}'/>";
	
	if(_fromSjFlag == "true" && isNewFlag){
		$("#receiveChange").show();
	}
	var type = $("#formType").val();
	if(type=="2"){
		$("#num").textbox({
		    required: true
		});
	}else{
		$("#num").textbox({
		    required: true,
		    validType:'valNumUnique',
		    validateOnBlur:true,
		    validateOnCreate:false
		});
	}
	
	//收编号码
	$("#dispatchOrg").textbox({
	    required: true,
	    editable:prEditFlag
	});
//	//分办人
//	$("#pressCorrector").textbox({
////	    required: true,
//	    editable:todoFlag
//	});	
	
	$("#docName").textbox({
	    required: true,
	    editable:prEditFlag
	});	
	
	//紧急程度，是否归档，保管期限
	$("#secretCode").combobox({
		editable:false,
		disabled:!editFlag
	});
	
	$("#emergencyCode").combobox({
		editable:false,
		required: true,
		validType: 'selectValueRequired',
		disabled:!editFlag
	});
	
	
	
/*	$("#archiveSaveDeadline").combobox({
		editable:false,
		required: true,
		validType: 'selectValueRequired',
		novalidate:true,
		disabled:!todoFlag
	});

	//归档分类
	$('#archiveCategoryId').combobox({
		required:true,
		editable:false, 
		onSelect:function(record){
			$("#archiveCategoryName").val(record.value==""?"":record.text);
		},
		disabled:!todoFlag
	});*/
	
	$("#isArchive").combobox({
		editable:false,
		required: true,
		validType: 'selectValueRequired',
		disabled:!editFlag,
		onSelect:function(record){
//			if(record.value=='1'){
//				$('#archiveSaveDeadline,#archiveCategoryId').combobox('enableValidation');
//			}else{
//				$('#archiveSaveDeadline,#archiveCategoryId').combobox('disableValidation');
//			}
		},
	});
	
	
	//摘要
	$("#receiveRemark").textbox({
		multiline:true,
		editable:editFlag,
		required:false
		
	});
	
//	//是否显示摘要
//	$("input[name='isReceiveRemark']").click(function(){
//		changeReceiveRemarkTR();
//	}).attr("disabled",!todoFlag);
//	changeReceiveRemarkTR();//初始化调用次，显示或者隐藏摘要
	$("#expeireTime").datebox({
		editable:false,
		disabled:!editFlag
	}).datebox('calendar').calendar({
        validator: function(value){
            var now = new Date();
            var d1 = new Date(now.getFullYear(), now.getMonth(), now.getDate())
            return value >= d1;
        }
    });
	$("#emergencyCode").combobox("setValue", '${docIssue.emergencyCode}'); 
	$("#isArchive").combobox("setValue", '${docIssue.isArchive}'); 
	$("#archiveSaveDeadline").combobox("setValue", '${docIssue.archiveSaveDeadline}'); 
	$("#secretCode").combobox("setValue", '${docIssue.secretCode}'); 
	
	$('#numLine').combobox({
		editable:false, 
		onChange:function(newVal,oldVal){
			buildDisplayNumberDiv($("#formType").val());
		}
	});
	$('#numLineName').combobox({
		editable:false, 
		onChange:function(record){
			buildDisplayNumberDiv($("#formType").val());
		}
	});
	
	if("<c:out value='${docIssue.docReceiveUuid}'/>"!=""){
		$("#traceSource").show();
	}
}

//下载附件
function fileUploadDownloadDocAttach(control,attachId,suffixName,attachName){
	var newFlag="";
	if("newFile"==$(control).parent("li").attr("class")){
		newFlag="1";
	}else{
		newFlag="0";
	}
	window.location.href =_synergyContext+"/basic/synAttach/downLoadFile?attachId=" + attachId + "&attachName="+encodeURIComponent(encodeURIComponent(attachName))+"&suffixName="+suffixName+"&newFlag="+newFlag;
}

function changeReceiveRemarkTR(){
	if($("input[name='isReceiveRemark']:checked").val()=="1"){
		$("#receiveRemark").textbox("enableValidation");
		$("#receiveRemark").css("width","85%");
		$("#receiveRemarkTR").show();
	}else{
		$("#receiveRemark").textbox("disableValidation");
		$("#receiveRemarkTR").hide();
	}
}

/*//查看正文公文
function showDocDocument(){
	var docId = $("#docId").val();
	//下载公文到app下
	$.ajax({//ajax保存表单基本信息
	   type: "POST",
	   url: "<c:url value='/receive/querySynOfficial' />",
	   data:"docId="+docId,
	   dataType: "json",
	   async:false,
	   success: function(msg){
	     if(msg.state=="200"){
	    	 var vHeight = window.screen.height -73 ;
//    		 var wordUrl =_synergyContext+"/basic/office/editOffice?docId=" + docId + "&fileReadOnly=true&notkHeigth="+vHeight;
	    	 var wordUrl =_synergyContext+"/basic/office/editOfficeNoDocId" + "?docId=" +docId + "&formId=-1&docType=done&fileReadOnly=true&notkHeigth="+vHeight;
    		 var winFeatures = "height="+vHeight+"px,width="+window.screen.width+"px,top=0,left=0,toolbar=no,menubar=no,scrollbars=no,resizable=no,location=no,status=no";
    		 window.open(wordUrl,'_blank',winFeatures);
	     }else{
	    	 $.messager.alert("提示","该公文没有正文");
	    	 return;
	     }
	   }
	});
}*/
function downloadOfficeFile(){
	window.location.href=_synergyContext+'/basic/office/downLoadFile?docId='+$("#docId").val()+"&officeName="+encodeURIComponent(encodeURIComponent($("#docName").textbox("getValue")));
}

/**
 * 批量下载文件（正文 + 附件）
 * @returns
 */
function batchDownLoadFile(){
	window.location.href=_synergyContext+'/basic/office/batchDownLoadFile?docId='+$("#docId").val()+"&officeName="+encodeURIComponent(encodeURIComponent($("#docName").textbox("getValue")));
}


/**
 * 收文转直接发文
 * @returns
 */
function _receiveChange(){
	var _docId = $("#docId").val();
	window.location = '<c:url value="/dtReceiveDocument/receiveChange"/>' + "?docId="+_docId;
}

function buildDisplayNumberDiv(type){
	var numberContent = "";
	if(type=="1"){
		numberContent = $("#numYear").val();
	}else if(type=="2"){
		numberContent = $("#numOrg").val()+"-"+$("#numYear").val()+"-"+$("#numMonth").val()
	}else if(type=="3"){
		numberContent = $('#numLine').combobox('getValue')+"-"+$('#numLineName').combobox('getValue')+"-"+$("#numYear").val()
	}else{
		alert("参数错误");
		return;
	}
	var data = "formId="+$("#formId").val()+"&numberContent="+numberContent+"&checkYear="+$("#numYear").val();
	$.ajax({  
		type: "POST",
		url:'<c:url value="/synNumber/getReceiveDisplayNumber"/>',
		data:data,
		async:false,
		//contentType: "application/x-www-form-urlencoded; charset=utf-8",
		success: function(json)
		{	
			if(json.state=="200"){
				$("#numberLogId").val(json.numberLogId);
				$("#numberId").val(json.numberId);
				$("#num").textbox("setValue",json.num);
				
			}else{
				$.messager.alert("提示","收文表单未绑定对应的收文编号或者未绑定权限！");
			}
			
			
		},
		error: function()
		{
			$.messager.alert("提示","编号获取失败！");
		}
    });
}
function getReceiveAdviceByIndex(index)
{
	$("#receiveAdviceTbody").html('<tr><td colspan="6" style="height:35px;" align=center ><img style="vertical-align:middle" src=<c:url value="/images/ajaxLoader.gif"/>>正在加载数据，请稍等！</td></tr>');
	$.ajax({
		type: "POST",
		url: "<c:url value='/receive/getAdviceByIndex/'/>"+index,
		data:"issueId=" + _issueId,
		dataType: 'json',
		success: function(json)
		{
			if(json != "" && json != null){
				initReceiveAdvice(json);
			} else {
				$("#receiveAdviceTbody").html('<tr><td colspan="6" align=center >无数据</td></tr>');
			}
		}
	});
}

function initReceiveAdvice(json)
{
	$('#receiveAdviceTbody').empty();
	var data = json.child;
	var totalLength=data.length+1;
	$.each( data, function(i, n){
		// 行号
		var num = '<td class="tdc"  style="text-align:center;height:35px;">'+(i+1)+'</td>';
		// 步骤
		var activeName;
//		if(n.roleTypeId == 'OrganizationalUnit')
//		{
//			activeName = '<td style="text-align:center;"> <a href="###" onclick="getAdviceByIndex('+n.index+')" >'+n.activeName+'</a></td>';
//		}
//		else
//		{
			activeName = '<td style="text-align:center;">'+n.activeName+'</td>';
	//	}
		
		// 状态
		var state = '<td style="text-align:center;">'+n.state+'</td>';
		// 修改按钮
		var editNoteBtn = '';
		// 意见
		var noteInfo = '';
		noteInfo = '<td>';
		if(n.signNoteInfo && n.signNoteInfo != "") {
			noteInfo += '<font color="#D94600">' + n.signNoteInfo + '</font>';
			noteInfo += '<BR />'
		}
		if(n.instructionsNoteInfo && n.instructionsNoteInfo != "") {
			noteInfo += '<font color="#D94600">' + n.instructionsNoteInfo + '</font>';
			noteInfo += '<BR />'
		}
//		if(viewCommentNote == "true") {
//			// 局长和局长秘书有权限看备注意见
//			if(n.commentNoteInfo && n.commentNoteInfo != "") {
//				noteInfo += '<font color="#6F00D2">' + n.commentNoteInfo + '</font>';
//				noteInfo += '<BR />'
//			}
//		}
		if(n.checkNoteInfo && n.checkNoteInfo != "") {
			noteInfo += '<font color="#820041">' + n.checkNoteInfo + '</font>';
			noteInfo += '<BR />'
		}
		if(n.discussionNoteInfo && n.discussionNoteInfo != "") {
			noteInfo += '<font color="#820041">' + n.discussionNoteInfo + '</font>';
			noteInfo += '<BR />'
		}
		if(n.dealNoteInfo) {
			noteInfo += n.dealNoteInfo;
		}
		noteInfo += '</td>';
		// 办理人
		var partyName = '<td style="text-align:center;">';
		if(n.hasSignature == 'true')
		{
			partyName = partyName+"<img width='135dbpx' height='88px' name=\"signatureImage\" src=\""+_oaContext+"/personSignatureController/getPersonSignature?personUuid="+n.partyId+"&1=1\" style=\"height:60px\" border=\"0\">";
		} else
		{
			partyName = n.partyName==null?"<td></td>":partyName+n.partyName;
		}
		if(n.hasDelegant == 'true')
		{
			partyName = partyName+'<br/>(代 '+n.activityId+' 办)';
		}
		partyName = (partyName==null?"":partyName)+'</td>';
		
		// 处理时间
		var fromDate = '<td style="text-align:center;">'+removeSecond(n.fromDate)+'<br/>';
		// 办结时间
		var endDate = removeSecond(n.endDate)+'</td>';
		var tr;
		if(i%2 != 0)
		{
			tr = '<tr bgcolor="#EEFFFF" >';
		}
		else
		{
			tr = '<tr>';
		}
		tr = tr+num+activeName+state+noteInfo+partyName+fromDate+endDate+'</tr>'
//		if(!sortDescFlag || i==0){
			$('#receiveAdviceTbody').append(tr);
//		}else{
//			$('#adviceTbody tr').first().before(tr);
//		}
	
		});
}
function _traceSource(){
	var url = "<c:url value='/receive/traceSource/' />"+_issueId;
	var winFeatures = "height=500px,width=1000px,top=50px,left=200px,toolbar=no,menubar=no,resizable=no,location=no,status=no,scrollbars=yes";
	window.open(url,'_blank',winFeatures);
}
function removeSecond(adviceTime)
{
	if(typeof(adviceTime) == "undefined"
		|| adviceTime.length == 0)
	{
		return "";
	} else
	{
		var markIndex = adviceTime.indexOf(":");
		if(markIndex > 0)
		{
			return adviceTime.substring(0, markIndex+3);
		} else
		{
			return adviceTime;
		}
	}
}

function isNumberText(z_check_value){  
    var z_reg = /^([0-9]{4})$/;  
    return z_reg.test($.trim(z_check_value));  
}
$.extend($.fn.validatebox.defaults.rules, { 
	valNumUnique: { 
		validator: function(value,param){
			if(!isNumberText(value)){
				$.fn.validatebox.defaults.rules.valNumUnique.message ="请输入4位数字字符串";
				return false;
			}
			var boolNum = true;
			var type = $("#formType").val();
　　　　　　　if(type=="1"){
　　　　　		$("#displayNumberReceive").val($("#numYear").val()+"-"+value);
　　　　　　　}else if(type=="2"){
　　　　　　　　	$("#displayNumberReceive").val($("#numOrg").val()+"-"+$("#numYear").val()+"-"+$("#numMonth").val()+"-"+value);
　　　　　　　}else if(type=="3"){
　　　　　　　　	$("#displayNumberReceive").val($('#numLine').combobox('getValue')+"-"+$('#numLineName').combobox('getValue')+"-"+$("#numYear").val()+"-"+value);
　　　　　　　}
　　　　　　　$.ajax({
				async:false,
　　　　　　　　	type:"POST",
　　　　　　　　	url:'<c:url value="/receive/valNumUnique"/>', 
　　　　　　　		data: "docId="+_issueId+"&displayNumberReceive="+$("#displayNumberReceive").val()+"&formId="+_formId,
　　　　　　　		success:function(msg){
　　　　　　　　		if(msg.state=="200"){
　　　　　　　　			   
　　　　　　　　		}else{
　　　　　　　　			$.fn.validatebox.defaults.rules.valNumUnique.message ="编号冲突，请修改！";
　　　　　　　　			boolNum = false;
　　　　　　　　		}										
　　　　　　　　	}
			});
			return boolNum;
		}, 
　　　　　message: "" 
	}

}); 